﻿using System;
using System.Configuration;
using System.Web;
using Core.AdminUser;

namespace Core.Authenticated
{
    public class AuthenticatedPage : System.Web.UI.Page
    {
        protected string ReturnUrl = string.Empty;

        public AdminUserObject CurrentUser
        {
            get
            {
                if (Context.Items[ConfigurationManager.AppSettings["SitePrefix"]] != null)
                    return (AdminUserObject)Context.Items[ConfigurationManager.AppSettings["SitePrefix"]];
                return null;
            }
            set
            {
                Context.Items.Remove(ConfigurationManager.AppSettings["SitePrefix"]);
                Context.Items[ConfigurationManager.AppSettings["SitePrefix"]] = value;
            }
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            ReturnUrl = Server.UrlEncode(Request.RawUrl);
            var context = HttpContext.Current;

            // Lưu ý đoạn này cần có trong webconfig để context.User.Identity.Name lấy được tên đăng nhập
            // <authentication mode="Forms">
            //  <forms loginUrl="login.aspx"/>      
            // </authentication>
            if (context.User.Identity.IsAuthenticated && context.User.Identity.Name.IndexOf(ConfigurationManager.AppSettings["SitePrefix"]) > -1)
            {
                var username = context.User.Identity.Name.Replace(ConfigurationManager.AppSettings["SitePrefix"], string.Empty);
                if (CurrentUser == null)
                    CurrentUser = AdminUserController.AdminUser_GetBy_Username_Status(username, AdminUserObject.IsActived + AdminUserObject.IsSuperAdministrator + AdminUserObject.IsSuspended);
            }
            else
            {
                Response.Redirect("/Login.aspx?returnUrl=" + ReturnUrl);
            }
        }    
    }
}
